package pers.goetboy.common.vaild;

import pers.goetboy.common.exception.BaseCommonException;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * isEnum 校验类
 *
 * @author goetb
 * @see IsEnum
 */
public class IsEnumValidator implements ConstraintValidator<IsEnum, Object> {
    private String method = "";
    private Class<?> aClass;

    @Override
    public void initialize(IsEnum constraintAnnotation) {
        aClass = constraintAnnotation.aClass();
        method = constraintAnnotation.method();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }
        if (!aClass.isEnum()) {
            throw new BaseCommonException("此类不是一个枚举类");
        }
        List<Method> methods = Arrays.stream(aClass.getMethods()).filter(o -> o.getName().equals(this.method)).collect(Collectors.toList());
        if (methods == null || methods.isEmpty()) {
            throw new BaseCommonException("枚举类中没有找到可以执行校验的方法");
        }

        if (methods.size() > 1) {
            throw new BaseCommonException("校验失败,找到多个同名方法");
        }
        try {
            return (boolean) methods.get(0).invoke(null, value);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new BaseCommonException(e);
        }


    }
}
